import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../models/wallet_model.dart';
import '../services/wallet_service.dart';
import '../services/blockchain_service.dart';
import '../constants/wallet_constants.dart';

/// 钱包状态管理
class WalletProvider extends ChangeNotifier {
  final WalletService _walletService = WalletService();
  final BlockchainService _blockchainService = BlockchainService();
  
  // 状态变量
  List<WalletModel> _wallets = [];
  WalletModel? _currentWallet;
  String _currentNetwork = 'ethereum';
  List<TokenModel> _tokens = [];
  List<TransactionModel> _transactions = [];
  bool _isLoading = false;
  String? _error;
  
  // Getters
  List<WalletModel> get wallets => _wallets;
  WalletModel? get currentWallet => _currentWallet;
  String get currentNetwork => _currentNetwork;
  List<TokenModel> get tokens => _tokens;
  List<TransactionModel> get transactions => _transactions;
  bool get isLoading => _isLoading;
  String? get error => _error;
  
  /// 初始化
  Future<void> initialize() async {
    try {
      _setLoading(true);
      await _loadWallets();
      await _loadCurrentNetwork();
      if (_wallets.isNotEmpty && _currentWallet == null) {
        _currentWallet = _wallets.first;
        await _loadWalletData();
      }
    } catch (e) {
      _setError('初始化失败: $e');
    } finally {
      _setLoading(false);
    }
  }
  
  /// 生成助记词
  Future<String> generateMnemonic() async {
    return _walletService.generateMnemonic();
  }
  
  /// 创建新钱包
  Future<void> createWallet({
    required String name,
    required String networkId,
    String? mnemonic,
    bool loadDataImmediately = false, // 是否立即加载数据
  }) async {
    print('==================== Provider: 创建钱包 ====================');
    print('📝 钱包名称: $name');
    print('🌐 网络: $networkId');
    
    try {
      _clearError();
      
      print('🔄 开始创建钱包...');
      final walletStartTime = DateTime.now();
      
      final wallet = await _walletService.createWallet(
        name: name,
        networkId: networkId,
        mnemonic: mnemonic,
      );
      
      final walletEndTime = DateTime.now();
      print('⏱️ 钱包创建耗时: ${walletEndTime.difference(walletStartTime).inMilliseconds}ms');
      
      _wallets.add(wallet);
      
      print('💾 保存钱包到本地...');
      await _saveWallets();
      print('✅ 钱包已保存');
      
      // 如果是第一个钱包，设置为当前钱包
      if (_currentWallet == null) {
        _currentWallet = wallet;
        
        // 根据参数决定是否立即加载数据（查询余额等）
        if (loadDataImmediately) {
          print('🔄 立即加载钱包数据...');
          await _loadWalletData();
        } else {
          print('⏭️ 跳过立即加载数据，将在返回主页后加载');
          // 不立即加载数据，返回主页后会自动加载
        }
      }
      
      print('✅ Provider: 钱包创建完成！');
      print('==================================================');
      
      notifyListeners();
    } catch (e, stackTrace) {
      print('❌ Provider: 创建钱包失败！');
      print('❌ 错误: $e');
      print('❌ 堆栈: $stackTrace');
      print('==================================================');
      _setError('创建钱包失败: $e');
      rethrow;
    }
  }
  
  /// 导入钱包
  Future<void> importWallet({
    required String name,
    required String networkId,
    required String mnemonic,
    bool loadDataImmediately = false, // 是否立即加载数据
  }) async {
    try {
      _clearError();
      
      final wallet = await _walletService.importWallet(
        name: name,
        networkId: networkId,
        mnemonic: mnemonic,
      );
      
      _wallets.add(wallet);
      await _saveWallets();
      
      if (_currentWallet == null) {
        _currentWallet = wallet;
        
        if (loadDataImmediately) {
          await _loadWalletData();
        }
      }
      
      notifyListeners();
    } catch (e) {
      _setError('导入钱包失败: $e');
      rethrow;
    }
  }
  
  /// 从私钥导入钱包
  Future<void> importWalletFromPrivateKey({
    required String name,
    required String networkId,
    required String privateKey,
    bool loadDataImmediately = false, // 是否立即加载数据
  }) async {
    try {
      _clearError();
      
      final wallet = await _walletService.importWalletFromPrivateKey(
        name: name,
        networkId: networkId,
        privateKey: privateKey,
      );
      
      _wallets.add(wallet);
      await _saveWallets();
      
      if (_currentWallet == null) {
        _currentWallet = wallet;
        
        if (loadDataImmediately) {
          await _loadWalletData();
        }
      }
      
      notifyListeners();
    } catch (e) {
      _setError('导入钱包失败: $e');
      rethrow;
    }
  }
  
  /// 切换当前钱包
  Future<void> switchWallet(WalletModel wallet) async {
    print('==================== 切换钱包 ====================');
    print('📝 切换到: ${wallet.name}');
    print('📍 地址: ${wallet.address}');
    
    try {
      // 不设置全局 loading，避免 UI 闪烁
      _clearError();
      
      // 立即切换当前钱包，先显示新钱包
      _currentWallet = wallet;
      notifyListeners(); // 立即刷新UI显示新钱包
      
      print('🔄 开始加载钱包数据...');
      // 后台加载钱包数据
      await _loadWalletData();
      
      print('✅ 钱包切换成功！');
      print('==================================================');
      
      notifyListeners(); // 数据加载完成后再次刷新
    } catch (e) {
      print('❌ 切换钱包失败: $e');
      print('==================================================');
      _setError('切换钱包失败: $e');
    }
  }
  
  /// 切换网络
  Future<void> switchNetwork(String networkId) async {
    print('==================== 切换网络 ====================');
    print('🌐 切换到: $networkId');
    
    try {
      // 不设置全局 loading，避免 UI 闪烁
      _clearError();
      
      // 立即切换网络
      _currentNetwork = networkId;
      await _saveCurrentNetwork();
      notifyListeners(); // 立即刷新UI显示新网络
      
      // 如果有当前钱包，后台重新加载数据
      if (_currentWallet != null) {
        print('🔄 开始重新加载钱包数据...');
        await _loadWalletData();
        notifyListeners(); // 数据加载完成后再次刷新
        print('✅ 网络切换成功！');
      }
      
      print('==================================================');
    } catch (e) {
      print('❌ 切换网络失败: $e');
      print('==================================================');
      _setError('切换网络失败: $e');
    }
  }
  
  /// 删除钱包
  Future<void> deleteWallet(WalletModel wallet) async {
    try {
      _setLoading(true);
      _clearError();
      
      await _walletService.deleteWallet(wallet.id);
      _wallets.removeWhere((w) => w.id == wallet.id);
      await _saveWallets();
      
      if (_currentWallet?.id == wallet.id) {
        _currentWallet = _wallets.isNotEmpty ? _wallets.first : null;
        if (_currentWallet != null) {
          await _loadWalletData();
        } else {
          _tokens.clear();
          _transactions.clear();
        }
      }
      
      notifyListeners();
    } catch (e) {
      _setError('删除钱包失败: $e');
    } finally {
      _setLoading(false);
    }
  }
  
  /// 刷新钱包数据
  Future<void> refreshWalletData() async {
    if (_currentWallet == null) return;
    
    print('==================== 刷新钱包数据 ====================');
    print('📍 当前钱包: ${_currentWallet?.name}');
    print('🌐 当前网络: $_currentNetwork');
    
    try {
      // 不设置全局 loading，避免 UI 闪烁
      _clearError();
      
      print('🔄 开始刷新数据...');
      // 后台刷新数据
      await _loadWalletData();
      
      print('✅ 数据刷新成功！');
      print('==================================================');
      
      notifyListeners(); // 数据加载完成后刷新
    } catch (e) {
      print('❌ 刷新数据失败: $e');
      print('==================================================');
      _setError('刷新数据失败: $e');
    }
  }
  
  /// 发送交易
  Future<String> sendTransaction({
    required String to,
    required String amount,
    required String privateKey,
  }) async {
    try {
      _setLoading(true);
      _clearError();
      
      final hash = await _blockchainService.sendTransaction(
        to: to,
        amount: amount,
        privateKey: privateKey,
        networkId: _currentNetwork,
      );
      
      // 刷新数据
      await _loadWalletData();
      
      return hash;
    } catch (e) {
      _setError('发送交易失败: $e');
      rethrow;
    } finally {
      _setLoading(false);
    }
  }
  
  /// 发送代币交易
  Future<String> sendTokenTransaction({
    required String tokenAddress,
    required String to,
    required String amount,
    required String privateKey,
    required int decimals,
  }) async {
    try {
      _setLoading(true);
      _clearError();
      
      final hash = await _blockchainService.sendTokenTransaction(
        tokenAddress: tokenAddress,
        to: to,
        amount: amount,
        privateKey: privateKey,
        networkId: _currentNetwork,
        decimals: decimals,
      );
      
      // 刷新数据
      await _loadWalletData();
      
      return hash;
    } catch (e) {
      _setError('发送代币交易失败: $e');
      rethrow;
    } finally {
      _setLoading(false);
    }
  }
  
  /// 获取当前网络配置
  NetworkConfig? getCurrentNetworkConfig() {
    return WalletConstants.supportedNetworks[_currentNetwork];
  }
  
  /// 获取总资产价值
  String getTotalAssetValue() {
    double total = 0.0;
    for (final token in _tokens) {
      if (token.price != null) {
        final price = double.tryParse(token.price!) ?? 0.0;
        final balance = double.tryParse(token.balance) ?? 0.0;
        total += price * balance;
      }
    }
    return total.toStringAsFixed(2);
  }
  
  /// 加载钱包数据
  Future<void> _loadWalletData() async {
    if (_currentWallet == null) return;
    
    try {
      // 获取原生代币余额
      final balance = await _blockchainService.getBalance(
        _currentWallet!.address,
        _currentNetwork,
      );
      
      // 更新原生代币
      final networkConfig = getCurrentNetworkConfig();
      if (networkConfig != null) {
        final nativeToken = TokenModel(
          symbol: networkConfig.symbol,
          name: networkConfig.name,
          contractAddress: '',
          decimals: networkConfig.decimals,
          balance: balance,
          networkId: _currentNetwork,
        );
        
        _tokens = [nativeToken];
      }
      
      // 加载交易历史
      _transactions = await _blockchainService.getTransactionHistory(
        _currentWallet!.address,
        _currentNetwork,
      );
      
    } catch (e) {
      _setError('加载钱包数据失败: $e');
    }
  }
  
  /// 加载钱包列表
  Future<void> _loadWallets() async {
    try {
      final box = await Hive.openBox<WalletModel>('wallets');
      _wallets = box.values.toList();
    } catch (e) {
      _wallets = [];
    }
  }
  
  /// 保存钱包列表
  Future<void> _saveWallets() async {
    try {
      final box = await Hive.openBox<WalletModel>('wallets');
      await box.clear();
      for (final wallet in _wallets) {
        await box.put(wallet.id, wallet);
      }
    } catch (e) {
      // 忽略保存错误
    }
  }
  
  /// 加载当前网络
  Future<void> _loadCurrentNetwork() async {
    try {
      final box = await Hive.openBox('settings');
      _currentNetwork = box.get('current_network', defaultValue: 'ethereum');
    } catch (e) {
      _currentNetwork = 'ethereum';
    }
  }
  
  /// 保存当前网络
  Future<void> _saveCurrentNetwork() async {
    try {
      final box = await Hive.openBox('settings');
      await box.put('current_network', _currentNetwork);
    } catch (e) {
      // 忽略保存错误
    }
  }
  
  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }
  
  /// 设置错误
  void _setError(String error) {
    _error = error;
    notifyListeners();
  }
  
  /// 清除错误
  void _clearError() {
    _error = null;
  }
  
  @override
  void dispose() {
    _blockchainService.dispose();
    super.dispose();
  }
}
